package com.coin.service;

import com.coin.common.AccountType;
import com.coin.common.MachineUseStatus;
import com.coin.common.MemberType;
import com.coin.dao.account.AccountMapper;
import com.coin.dao.account.MachineMapper;
import com.coin.dao.model.Account;
import com.coin.dao.model.Machine;
import com.coin.dao.model.Member;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;

/**
 * Created by chenhao on 2017/5/18.
 */
@Service
@Transactional
public class MachineService {
    @Resource
    private MachineMapper machineMapper;
    @Resource
    private AccountMapper accountMapper;

    public boolean initMachine(Long machineNumber) {
        //先插入主表生成id 再按照id散列到不同的分区表上
        Machine machine = new Machine();
        machine.setCreateTime(new Date());
        machine.setMachineNumber(machineNumber.intValue());
        machine.setUseStatus(MachineUseStatus.common);
        boolean k = machineMapper.insertMainTable(machine) == 1;
        //散列
        machine.setTableId(String.valueOf(machineNumber % 16));
        boolean s = machineMapper.insert(machine) == 1;

        //每一台机器初始化的时候需要插入一条账户信息
        Account account = new Account();
        account.setMemberId(machineNumber);
        account.setMemberType(MemberType.machine);
        account.setAccountType(AccountType.machineBalance);
        account.setCreateTime(new Date());
        account.setUpdateTime(new Date());
        account.setBalance(BigDecimal.ZERO);
        accountMapper.insertMainTable(account);

        account.setTableId(String.valueOf(account.getId() % 16));
        boolean t = 1 == accountMapper.insert(account);

        return s && k && t;
    }
}
